package wang.chunfan.springcoud.learning.api.gateway.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import reactor.core.publisher.Mono;

/**
 * @version 1.0
 * @Author wangchunfan
 * @Date 2020/5/26 20:49
 * 限流策略
 **/
@Configuration
public class RedisRateLimiterConfig {

    /**
     * 根据 url 限流
     */
    @Primary // 3 个 bean 都实现了相同的接口，在 autowired 注入时选择 Primary
    @Bean
    KeyResolver apiKeyResolver() {
        //按URL限流,即以每秒内请求数按URL分组统计，超出限流的url请求都将返回429状态
        return exchange -> Mono.just(exchange.getRequest().getPath().toString());
    }
    /**
     * 根据请求参数限流
     */
    @Bean
    public KeyResolver usernameKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("username"));
    }

    /**
     * 根据请求 ip 限流
     * */
    @Bean
    public KeyResolver ipKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
    }
}
